package com.cloud.template.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;

/**
 * netty客户端（使用DelimiterBasedFrameDecoder解决tcp的粘包和拆包）
 * DelimiterBasedFrameDecoder是以设置的字符为结束标志的解码器，
 * 设置的长度是单条消息的最大长度，当达到该长度后还没有查到分隔符就抛出异常
 * StringDecoder是将接收到的对象转换成字符串
 * Created by Viole on 2018/1/3.
 */
public class DelimiterTcpNettyClient {

    private final String host;
    private final int port;

    public DelimiterTcpNettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.remoteAddress(new InetSocketAddress(host, port));
            b.handler(new ChannelInitializer<SocketChannel>() {
                public void initChannel(SocketChannel ch) throws Exception {
                    //使用DelimiterBasedFrameDecoder和StringDecoder结局tcp的粘包和拆包
                    ByteBuf byteBuf = Unpooled.copiedBuffer("$_".getBytes());
                    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf));
                    ch.pipeline().addLast(new StringDecoder());

                    ch.pipeline().addLast(new DelimiterClientHandler());
                }
            });
            ChannelFuture f = b.connect().sync();
            f.addListener(new ChannelFutureListener() {

                public void operationComplete(ChannelFuture future) throws Exception {
                    if(future.isSuccess()){
                        System.out.println("client connected");
                    }else{
                        System.out.println("server attemp failed");
                        future.cause().printStackTrace();
                    }
                }
            });
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {

        new DelimiterTcpNettyClient("127.0.0.1", 8000).start();
    }
}
